<style rel="stylesheet/scss" lang="scss">
  .el-dialog__body {
    padding-bottom: 10px;
  }
</style>

<template>
  <div class="app-container">
    <div class="filter-container" style="margin-bottom: 20px; font:16px/1 'Microsoft YaHei'; color:#333;">我的应用</div>
    <div class="filter-container" style="margin-bottom: 20px; text-align: right;">
      <el-button class="filter-item" style="margin-left: 10px;" @click="$router.push('/app/add')" type="primary" icon="el-icon-plus" v-if="hasPower('/app/add')">添加应用</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="UpperFrame(true)" type="primary"  v-if="hasPower('/app/enable')" plain>恢复</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="UpperFrame(false)" type="primary" v-if="hasPower('/app/enable')" plain>暂停</el-button>
      <el-button class="filter-item" @click="handleRemove()" type="danger" icon="el-icon-delete" v-if="hasPower('/app/remove')">删除</el-button>
    </div>
    <el-table :data="data.list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" width="50"></el-table-column>
      <el-table-column type="index" label="编号" align="center" width="50"></el-table-column>
      <el-table-column label="应用名称" align="" width="180">
        <template slot-scope="scope">
          {{scope.row.name}}
        </template>
      </el-table-column>
      <el-table-column label="回调接口" align="">
        <template slot-scope="scope" v-if="scope.row.hooks">
          <span v-for="i in scope.row.hooks" v-if="scope.row.hooks.length > 0" style="margin-right:10px;">{{logTypePush[i]}}</span>
          <span v-if="scope.row.hooks.length === 0">-</span>
        </template>
      </el-table-column>
      <el-table-column label="服务" align="">
        <template slot-scope="scope" v-if="scope.row.apis">
          <span v-for="i in scope.row.apis" v-if="scope.row.apis.length > 0" style="margin-right:10px;">{{logTypeApi[i]}}</span>
          <span v-if="scope.row.apis.length === 0">-</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="状态" align="center" width="80">
        <template slot-scope="scope">
         <span :type="scope.row.status | statusFilter">{{scope.row.enable ? '有效' : '暂停'}}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" prop="created_at" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="$router.push({path: '/app/edit', query: {_id: scope.row._id}})" v-if="hasPower('/app/edit')">编辑</el-button>
          <el-button type="" size="mini" @click="$router.push({path: '/app/show', query: {_id: scope.row._id}})" v-if="hasPower('/app/show')">查看</el-button>
          <el-button type="" size="mini" @click="handleRoleOpen(scope.row, 'hooks')" v-if="hasPower('appPush')">推送配置</el-button>
          <el-button type="" size="mini" @click="handleRoleOpen(scope.row, 'apis')" v-if="hasPower('appApi')">接口配置</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top:30px;"
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="data.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="data.limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="data.total">
    </el-pagination>

    <el-dialog title="接口配置" :visible.sync="dialogRole">
      <div class="">
        <template>
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="checkVal" style="padding: 20px 0;" @change="handleCheckChange">
            <el-checkbox v-for="(o, i) in checkOpts" :key="i" :label="i">{{o}}</el-checkbox>
          </el-checkbox-group>
        </template>
      </div>
      <el-button type="success" @click="handleRoleUp">确定</el-button>
  </el-dialog>

  </div>

</template>

<script>

import { getList, postOne, appEnable, remove } from '@/api/app'
import { logTypeApi, logTypePush } from '@/utils/auth'

export default {
  data() {
    return {
      list: null,
      listLoading: true,
      data: {
        limit: 10,
        total: 0,
        page: 1
      },
      edit: '',
      form: {},
      listQuery: {},
      checkOpts: {},
      checkAll: false,
      checkVal: [],
      isIndeterminate: false,
      listSelect: [],
      logTypeApi,
      logTypePush,
      dialogRole: false
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  created() {
    if (this.$route.query.edit) this.listQuery.edit = this.$route.query.edit
    this.fetchData()
  },
  methods: {
    handleCheckAllChange(val) {
      this.checkVal = val ? Object.keys(this.checkOpts) : []
      this.isIndeterminate = false
    },
    handleCheckChange(val) {
      const num = val.length
      const total = Object.keys(this.checkOpts).length
      this.checkAll = num === total
      this.isIndeterminate = num > 0 && num < total
    },
    handleRoleOpen(o, type) {
      this.checkOpts = type === 'hooks' ? logTypePush : logTypeApi
      this.edit = type
      this.dialogRole = true
      this.form = Object.assign({}, o)
      this.checkVal = o[type]
      const num = this.checkVal.length
      const total = Object.keys(this.checkOpts).length
      this.checkAll = num === total
      this.isIndeterminate = num > 0 && num < total
    },
    handleRoleUp() {
      var vals = []
      this.checkVal.forEach(v => {
        if (this.checkOpts[v]) vals.push(v)
      })
      var post = {}
      post[this.edit] = vals
      postOne({
        _id: this.form._id
      }, post).then(response => {
        if (response.code === 30000) {
          this.$message({
            type: 'success',
            message: '更新成功!'
          })
          this.type = this.$route.query.type
          this.dialogRole = false
          this.fetchData()
        } else {
          this.$message({
            type: 'info',
            message: '更新失败!'
          })
        }
      })
    },
    handleSelectionChange(val) {
      this.listSelect = val
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },
    UpperFrame(o) {
      var _ids = []
      this.listSelect.forEach((v) => {
        _ids.push(v._id)
      })
      if (_ids.length < 1) {
        return this.$message({
          type: 'info',
          message: '请选择需要操作的应用!'
        })
      }
      this.$confirm('确定对选中应用进行此操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        appEnable(_ids, o).then(res => {
          if (res.code !== 30000) {
            return this.$message({
              type: 'error',
              message: '请求失败'
            })
          }
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.fetchData()
        })
      })
    },
    handleRemove(o) {
      var _ids = []
      this.listSelect.forEach((v) => {
        _ids.push(v._id)
      })
      if (o) {
        _ids = [o._id]
      }
      if (_ids.length < 1) {
        return this.$message({
          type: 'info',
          message: '请选择需要删除的应用!'
        })
      }
      this.$confirm('确认继续删除选中的应用?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        remove({
          _id: _ids
        }).then(res => {
          if (res.code !== 30000) {
            return this.$message({
              type: 'error',
              message: '请求失败'
            })
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.fetchData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    fetchData(con) {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        for (var i in response.data) {
          this[i] = response.data[i]
        }
        this.data = response.data
        this.listLoading = false
      })
    }
  }
}
</script>
